package com.zecan.blog.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.zecan.blog.dao.ChattingRecordsMapper;
import com.zecan.blog.dao.FollowMapper;
import com.zecan.blog.entity.ChattingRecords;
import com.zecan.blog.entity.Follow;
import com.zecan.blog.rabbitmq.event.ChatRoomEvent;
import com.zecan.blog.rabbitmq.event.FollowEvent;
import com.zecan.blog.rabbitmq.event.SendEmailEvent;
import com.zecan.blog.utils.BlogConstant;
import com.zecan.blog.utils.MailSendUtil;
import com.zecan.blog.utils.RedisUtils;
import com.zecan.blog.utils.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * rabbitmq 消费者
 * @ClassName BlogMqConsumer
 * @Description
 * @date 2022/11/24 19:25
 * @Version 1.0
 */
@Component
public class BlogMqConsumer {


    @Resource
    private RedisUtils redisUtils;

    @Resource
    private MailSendUtil mailSendUtil;


    @Resource
    private FollowMapper followMapper;

    @Resource
    private ChattingRecordsMapper chattingRecordsMapper;

    /**
     *
     * @param message 消息
     * @param channel 通道
     */
    @RabbitListener(queues = BlogConstant.RABBITMQ_CHATROOM_QUEUE)
    public void handlerChatMessage(Message message, Channel channel) {

        try {
            // 将聊天记录存储一天  将数据进行转移直接保存在redis中
            ChatRoomEvent chatRoomEvent = JSON.parseObject(message.getBody(),ChatRoomEvent.class);
            if(chatRoomEvent.getChatRoomType().equals(0)) {
                redisUtils.listSet(BlogConstant.CHAT_ROOM,chatRoomEvent,86400);
                // 消息的标识，false只确认当前一个消息收到，true确认所有consumer获得的消息（成功消费，消息从队列中删除 ）
                // message.getMessageProperties().getDeliveryTag() 当前消息的唯一标识
            }else {
                // 将私人聊天室的内容保存到数据库中
                chattingRecordsMapper.addChattingRecords( ChattingRecords.builder()
                                .recordContent(chatRoomEvent.getContent())
                                .recordUsers(chatRoomEvent.getUsers())
                                .recordReceiveUserId(chatRoomEvent.getReceiveUserId())
                                .recordUserId(chatRoomEvent.getUserId())
                                .recordCreateTime(StringUtils.dateFormat(new Date()))
                                .recordStatus(chatRoomEvent.getStatus())
                        .build());
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RabbitListener(queues = BlogConstant.RABBITMQ_SEND_EMAIL_QUEUE)
    public void handlerEmailMessage(Message message, Channel channel) {

        try {
            SendEmailEvent sendEmailEvent = JSONObject.parseObject(message.getBody(), SendEmailEvent.class);
            mailSendUtil.sendMail(sendEmailEvent);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RabbitListener(
            queues = {BlogConstant.RABBITMQ_FOLLOW_USER_QUEUE}
    )
    public void handleFollowMessage(Message message, Channel channel) {
        try {
            FollowEvent followEvent = JSONObject.parseObject(message.getBody(), FollowEvent.class);

            // 数据获取
            Integer followUserId = followEvent.getFollowUserId();
            String followUserAvatar = followEvent.getFollowUserAvatar();
            Integer followerUserId = followEvent.getFollowerUserId();
            String followerUserAvatar = followEvent.getFollowerUserAvatar();

            // 判断当前是否是第一次关注
            if (followEvent.isFirst()) {
                this.followMapper.insertFollow(
                        Follow.builder().followerUserAvatar(followerUserAvatar).
                                followUserId(followUserId).followerUserId(followerUserId).
                                followUserAvatar(followUserAvatar).followCreateTime(StringUtils.dateFormat(new Date())).build());
            } else {
                // 如果不是第一次关注则直接修改状态
                this.followMapper.updateFollowStatus(followUserId, followerUserId);
            }
            // 保存到redis中
            this.redisUtils.hashSet(StringUtils.concatRedisViewKey(followUserId), StringUtils.concatRedisViewHashKey(followUserId, followerUserId), followEvent, -1L);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException var8) {
            var8.printStackTrace();
        }

    }

    @RabbitListener(
            queues = {BlogConstant.RABBITMQ_UNFOLLOW_USER_QUEUE}
    )
    public void handleUnFollowMessage(Message message, Channel channel) {
        try {
            // 删除redis中对应的数据 与 修改数据库中关注信息
            FollowEvent followEvent = JSONObject.parseObject(message.getBody(), FollowEvent.class);
            Integer followUserId = followEvent.getFollowUserId();
            Integer followerUserId = followEvent.getFollowerUserId();
            this.redisUtils.delHash(StringUtils.concatRedisViewKey(followUserId), StringUtils.concatRedisViewHashKey(followUserId, followerUserId));
            this.followMapper.updateUnFollowStatus(followUserId, followerUserId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }

}
